package net.netca.bmps.userservice.servicelayer;

import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.security.cert.CertificateFactory;
import java.security.cert.X509Certificate;

import net.netca.bmps.userservice.bo.CertInfo;
import net.netca.bmps.userservice.service.UserService;
import net.netca.gdltax.bpms.webservice.CertServiceClient;
import net.netca.gdltax.bpms.webservice.CertServicePortType;
import net.netca.secuInter.X509PubKeyCertificate;
import net.netca.testwebservice.bo.XMLConfig;

import org.apache.commons.lang.StringUtils;

public class UserServiceImpl implements UserService {
	// private static final String filename="ws.properties";
	//private static String serviceurl = "http://192.168.0.37:8082/businessmanage/services/CertService";
	// private static String serviceurl = "http://localhost:8090/businessmanage/services/CertService";
	
	private static  String serviceurl = XMLConfig.getInstance().getUrl();
	
	private CertServicePortType stub = getStub();
	private static CertificateFactory cf;

	public CertInfo getPersonalCert(String reqno, int keytype, String keysn)
			throws Exception {
		return stub.getPersonalCert(reqno, keytype, keysn);
	}

	public boolean updateInstall(int status, int id) throws Exception {
		return stub.updateInstall(status, id);
	}

	private CertServicePortType getStub() {
		try {
			CertServiceClient client = new CertServiceClient(serviceurl);
			CertServicePortType service = client.getCertServiceHttpPort();
			return service;

		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}
	}

	public X509PubKeyCertificate getNetCACert(byte[] cert) throws Exception {
		if (cert == null)
			return null;
		InputStream is = null;
		X509Certificate x509cert = null;
		X509PubKeyCertificate netcaCert = null;
		try {
			is = new ByteArrayInputStream(cert);
			cf = CertificateFactory.getInstance("X.509");
			x509cert = (X509Certificate) cf.generateCertificate(is);
			netcaCert = new X509PubKeyCertificate(x509cert);
			return netcaCert;
		} catch (Exception e) {
			e.printStackTrace();
			throw e;
		} finally {
			if (is != null)
				is.close();
		}
	}

	public String getCanameByReqno(String reqno) throws Exception {
		if (StringUtils.isEmpty(reqno))
			return "";
		String name = stub.getCanameByReqno(reqno);
		return name;
	}
}
